const Service = require('egg').Service;

class UserService extends Service {
  async testName(name) {
    const ctx = this.ctx;
    const list = await ctx.model.User.findAll({
      attributes: ['username'],
      where: {
        username: name
      }
    });
    return list;
  }

  async findList(obj) {
    const ctx = this.ctx;
    const list = await ctx.model.User.findAndCountAll(obj);
    return list;
  }

  async findUser(name) {
    const ctx = this.ctx;
    const one = await ctx.model.User.findOne({
      attributes: {
        exclude: ['password']
      },
      where: {
        username: name
      }
    });
    return one;
  }

  async findUserPass(name) {
    const ctx = this.ctx;
    const one = await ctx.model.User.findOne({
      where: {
        username: name
      }
    });
    return one;
  }

  async findUserId(id) {
    const ctx = this.ctx;
    const one = await ctx.model.User.findByPk(id, {
      attributes: ['id', 'username', 'avatar', 'type']
    });
    return one;
  }

  async createUser(obj) {
    const ctx = this.ctx;
    await ctx.model.User.create(obj);
  }

  async editUser(form, id) {
    const ctx = this.ctx;
    await ctx.model.User.update(form, {
      where: {
        id: id
      }
    });
  }

  async deleteUser(id) {
    const ctx = this.ctx;
    await ctx.model.User.destroy({
      where: {
        id: id
      }
    });
  }

  async batchDeleteUsers(ids) {
    const { Op } = this.app.Sequelize;
    const ctx = this.ctx;
    await ctx.model.User.destroy({
      where: {
        id: {
          [Op.in]: ids
        }
      }
    });
  }
}

module.exports = UserService;